<template>
    <DrawStyleEdit v-if="graphic" />
</template>
<script setup>
import { onMounted, markRaw, ref, nextTick, onBeforeMount } from "vue";
import useDrawStore from "./drawStore";
import AsyncComp from "@/utils/AsyncComp";
import { storeToRefs } from "pinia";
import styles from "./styles";
import { cloneDeep } from "lodash";

const DrawStyleEdit = AsyncComp(() => import("./DrawStyleEdit.vue"));

const drawStore = useDrawStore();

const { graphic } = storeToRefs(drawStore);

let drawerLayer;

const emits = defineEmits(["load"]);

onMounted(() => {
    // init();
    emits("load");
});

//是否可编辑
const hasEdit = ref(false);
//初始化
const init = (_data, _hasEdit) => {
    hasEdit.value = _hasEdit;
    drawerLayer = new mars3d.layer.GraphicLayer({
        data: _data, //自动加载的数据
        hasEdit: _hasEdit, //是否可编辑
        isAutoEditing: true, // 绘制完成后是否自动激活编辑
        contextmenuItems: {}, // 关闭右键菜单
    });
    window.mapViewer.addLayer(drawerLayer);

    //添加点击事件
    drawerLayer.on(mars3d.EventType.click, async (e) => {
        if (!hasEdit.value) return;
        const _graphic = e.graphic;
        if (graphic.value?.id === _graphic.id) return;
        drawStore.setGraphic(null);
        await nextTick();
        drawStore.setGraphic(markRaw(_graphic));
    });

    //停止编辑
    drawerLayer.on(
        [mars3d.EventType.editStop, mars3d.EventType.removeGraphic],
        (e) => {
            drawStore.setGraphic(null);
        }
    );
};

//点击开始绘制
const onDrawStart = (type, style) => {
    drawStore.setGraphic(null);
    let _style = cloneDeep({
        ...styles[type]["defaultStyle"],
        ...style,
    });
    drawerLayer
        .startDraw({
            type,
            hasEdit: true,
            style: _style,
        })
        .then((_graphic) => {
            drawStore.setGraphic(markRaw(_graphic));
        });
};

//清除图层内容
const clearLayer = () => {
    drawerLayer && drawerLayer.clear();
};

//移除图层
const onExit = () => {
    drawerLayer && drawerLayer.remove();
    drawStore.setGraphic(null);
};

onBeforeMount(() => {
    //组件卸载，移除图层
    onExit();
});

//点击保存
const onSave = (callback) => {
    let json = drawerLayer.toJSON();
    callback(json);
};

defineExpose({
    init,
    onDrawStart,
    onSave,
    onExit,
    clearLayer,
});
</script>
<style lang="less" scoped>
.drawer-page {
    position: fixed;
    top: 20px;
    left: 20px;
    z-index: 1001;
}
</style>
